package com.zznzzn.myweb.controller;

import com.zznzzn.myweb.exceptions.ServiceException;
import com.zznzzn.myweb.pojo.Item;
import com.zznzzn.myweb.pojo.Order;
import com.zznzzn.myweb.pojo.RespModel;
import com.zznzzn.myweb.pojo.User;
import com.zznzzn.myweb.service.ItemService;
import com.zznzzn.myweb.service.OrderService;
import com.zznzzn.myweb.service.UserService;
import com.zznzzn.myweb.util.Base64Util;
import com.zznzzn.myweb.util.RespHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private UserService userService;

    @PostMapping("/placeOrder")
    public RespModel<Object> placeOrder(
            @RequestParam("from") String fromid,@RequestParam("to") String toid,
            @RequestParam("itemid") String itemid,@RequestParam("receid") String receid
    ){
       try{
           Order order = new Order();
           order.setOrderid(Base64Util.newUUID());
           order.setFromid(fromid);
           order.setToid(toid);
           order.setItemid(itemid);
           order.setReceid(receid);
           order.setCreatetime(new Date());
           orderService.placeOrder(order);
           itemService.updateStatus(itemid,2);

           //todo reduce item


           return RespHelper.buildSuccess("创建订单成功");
       }catch (ServiceException e){
           return RespHelper.buildFailure(e.getMessage());
       }
    }

    @PostMapping("/getOrders")
    public RespModel<Object> getOrders(@RequestParam("uuid") String uuid,@RequestParam("side") String side){
        try{
            List<Order> orders ;
            if (side.equals("buy")){
                orders = orderService.getBuyOrders(uuid);
            }else if (side.equals("sell")){
                orders = orderService.getSellOrders(uuid);
            }else{
                return RespHelper.buildFailure("没有该选择");
            }
            Map<String,Object> map = new HashMap<>();
            List<Item> items = new ArrayList<>();
            List<User> users = new ArrayList<>();
            for (Order o:orders){
                items.add(itemService.getItemByItemid(o.getItemid()));
                if (side.equals("buy")) {
                    users.add(userService.harmless(userService.getUserById(o.getFromid())));
                }else{
                    users.add(userService.harmless(userService.getUserById(o.getToid())));
                }
            }

            map.put("orders",orders);
            map.put("items",items);
            map.put("users",users);

            return RespHelper.buildSuccess(map);
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/sendOrder")
    public RespModel<Object> sendOrder(
            @RequestParam("orderid") String orderid,@RequestParam("itemid") String itemid,
            @RequestParam("trackid") String trackid
    ){
        try{
            Order order = orderService.getOrderById(orderid);
            order.setSendtime(new Date());
            order.setStatus(1);
            order.setTrackid(trackid);
            orderService.updateOrder(order);
            //set to sended
            itemService.updateStatus(itemid,3);
            return RespHelper.buildSuccess("设置发货成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/disorder")
    public RespModel<Object> disorder(
            @RequestParam("orderid") String orderid,@RequestParam("itemid") String itemid
    ){
        try{
            orderService.disorder(orderid);
            //set to publish
            itemService.updateStatus(itemid,1);
            return RespHelper.buildSuccess("取消订单成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/confirmOrder")
    public RespModel<Object> confirmOrder(
            @RequestParam("orderid") String orderid,@RequestParam("itemid") String itemid
    ){
        try{
            Order order = orderService.getOrderById(orderid);
            order.setFinishtime(new Date());
            order.setStatus(2);
            orderService.updateOrder(order);
            //set to received
            itemService.updateStatus(itemid,4);
            return RespHelper.buildSuccess("确认收货成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/commentOrder")
    public RespModel<Object> commentOrder(
            @RequestParam("orderid") String orderid,@RequestParam("side") String side,@RequestParam("comment") String bcomment
    ){
        String comment = "";

        try {
            comment = Base64Util.fullDecode(bcomment);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try{
            Order order = orderService.getOrderById(orderid);
            if (side.equals("buy")){
                order.setFromcomment(comment);
            }else if(side.equals("sell")){
                order.setTocomment(comment);
            }
            if (order.getFromcomment() != null && order.getTocomment() != null){

                //add rank for each after finish
                Item item = itemService.getItemByItemid(order.getItemid());
                User to = userService.getUserById(order.getToid());
                to.setRank((int) (to.getRank()+item.getPrice()/100));
                userService.updateUser(to);
                User from = userService.getUserById(order.getFromid());
                from.setRank((int) (from.getRank()+item.getPrice()/100));
                userService.updateUser(from);

                order.setStatus(3);
            }
            orderService.updateOrder(order);
            return RespHelper.buildSuccess("评论成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/getOrderCounts")
    public RespModel<Object> getOrderCounts(@RequestParam("uuid") String uuid){
        try{
            int sell = orderService.getSellCount(uuid);
            int buy = orderService.getBuyCount(uuid);
            Map<String,Integer> map = new HashMap<>();
            map.put("sell",sell);
            map.put("buy",buy);
            return RespHelper.buildSuccess(map);
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }
}
